package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import com.cskaoyan.user.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * Auth: 杨宇健
 * Time: 2023/1/9 22:09
 * Description:
 **/

@RestController
@RequestMapping("user")
public class RegisterController {

    @Autowired
    IUserRegisterService userRegisterService;

    @Autowired
    IKaptchaService kaptchaService;


    /**
     * 验证验证码
     * 生成request
     * 交给serverice校验
     * @param
     * @return
     * @author 杨宇健
     * @since 2023/01/09 22:12
     */
    @PostMapping("register")
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest request){
        Set<String> set = map.keySet();
        UserRegisterRequest userRequest = new UserRegisterRequest();
        //for (String key : set) {
        userRequest.setUserName(map.get("userName"));
        userRequest.setUserPwd(map.get("userPwd"));
        userRequest.setCaptcha(map.get("captcha"));
        userRequest.setEmail(map.get("email"));
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");

        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();

        if (kaptcha_uuid == null || userRequest.getCaptcha() == null) {
            throw new ValidateException(SysRetCodeConstants.DATA_NOT_EXIST.getCode(), SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        }
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(userRequest.getCaptcha());
        kaptchaService.validateKaptchaCode(kaptchaCodeRequest);

        userRegisterService.register(userRequest);

        return new ResponseUtil().setData(null);
    }

    @GetMapping("verify")
    public ResponseData verify(@RequestParam("username") String username, @RequestParam("uuid") String uuid){
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUsername(username);
        userVerifyRequest.setUuid(uuid);
        userRegisterService.verify(userVerifyRequest);
        return  new ResponseUtil().setData(null);
    }
}
